package com.supermarket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.supermarket.entity.Bill;
import com.supermarket.entity.Provider;
import com.supermarket.mapper.BillMapper;
import com.supermarket.mapper.ProviderMapper;
import com.supermarket.service.BillService;
import com.supermarket.util.R;
import com.supermarket.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;



@Service
public class BillServiceImpl extends ServiceImpl<BillMapper, Bill> implements BillService {
    @Autowired
    private BillMapper billMapper;
    @Autowired
    private ProviderMapper providerMapper;

    @Override
    public List<Provider> getAllProviders() {
        // 使用MyBatis-Plus的baseMapper方式查询
        return providerMapper.selectList(null);
    }
    @Override
    public boolean existsByBillCode(String billCode) {
        QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("billCode", billCode);
        return this.count(queryWrapper) > 0;
    }
    @Override
    public R<Object> getBillList(Integer currentPage, Integer pageSize, String billCode, String productName, String proName) {
        try {
            int start = (currentPage - 1) * pageSize;
            List<Bill> billList = billMapper.getBillList(start, pageSize, billCode, productName, proName);
            int totalCount = billMapper.getBillCount(billCode, productName, proName);
            Map<String, Object> data = new HashMap<>();

            data.put("list", billList);
            data.put("currentPage", currentPage);
            data.put("pageSize", pageSize);
            data.put("totalCount", totalCount);

            return R.createSuccess("00", "查询成功", data);
        } catch (Exception e) {
            e.printStackTrace();
            return R.createError(StatusCode.ERROR, "查询失败：" + e.getMessage());
        }
    }

    @Override
    public void addBill(Bill bill) {
        try {
            // 如果提供了供应商名称，根据名称获取供应商ID
            if (bill.getProName() != null && !bill.getProName().isEmpty()) {
                Provider provider = providerMapper.selectByProName(bill.getProName());
                if (provider != null) {
                    bill.setProviderId(provider.getId());
                    System.out.println("找到供应商: " + provider.getProName() + ", ID: " + provider.getId());
                } else {
                    System.err.println("未找到供应商: " + bill.getProName());
                    throw new RuntimeException("未找到指定的供应商: " + bill.getProName());
                }
            }
            
            // 设置创建时间
            bill.setCreationDate(new java.util.Date());
            
            // 打印调试信息
            System.out.println("准备保存账单: " + bill.getBillCode() + ", 供应商ID: " + bill.getProviderId());
            
            // 插入数据库
            billMapper.insert(bill);
            
            System.out.println("账单保存成功");
        } catch (Exception e) {
            System.err.println("保存账单失败: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public void updateBill(Bill bill) {
//        bill.setProName(providerMapper.selectById(billMapper.getBillById(bill.getId()).getProviderId()).getProName());
        bill.setProviderId(providerMapper.selectByProName(bill.getProName()).getId());
        billMapper.updateBill(bill);
    }

    @Override
    public Bill getBillById(Long id) {
        return billMapper.getBillById(id);
    }
    @Override
    public void deleteBill(Long id) {
        billMapper.deleteById(id);
    }
    
    @Override
    public R<Map<String, Object>> getDashboardStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 获取今日账单数量
            LocalDate today = LocalDate.now();
            String todayStr = today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            int todayCount = billMapper.getBillCountByDate(todayStr);
            Double todayAmount = billMapper.getTotalAmountByDate(todayStr);
            
            // 获取昨日账单数量
            LocalDate yesterday = today.minusDays(1);
            String yesterdayStr = yesterday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            int yesterdayCount = billMapper.getBillCountByDate(yesterdayStr);
            Double yesterdayAmount = billMapper.getTotalAmountByDate(yesterdayStr);
            
            // 获取本周账单数量
            LocalDate weekStart = today.with(java.time.DayOfWeek.MONDAY);
            String weekStartStr = weekStart.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String todayEndStr = today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            int thisWeekCount = billMapper.getBillCountByDateRange(weekStartStr, todayEndStr);
            Double thisWeekAmount = billMapper.getTotalAmountByDateRange(weekStartStr, todayEndStr);
            
            // 获取本月账单数量
            LocalDate monthStart = today.withDayOfMonth(1);
            String monthStartStr = monthStart.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            int thisMonthCount = billMapper.getBillCountByDateRange(monthStartStr, todayEndStr);
            Double thisMonthAmount = billMapper.getTotalAmountByDateRange(monthStartStr, todayEndStr);
            
            // 获取最近7天的账单数量趋势
            List<Integer> weeklyData = new ArrayList<>();
            List<String> weeklyLabels = new ArrayList<>();
            for (int i = 6; i >= 0; i--) {
                LocalDate date = today.minusDays(i);
                String dateStr = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                int count = billMapper.getBillCountByDate(dateStr);
                weeklyData.add(count);
                weeklyLabels.add(date.format(DateTimeFormatter.ofPattern("MM/dd")));
            }
            
            // 获取最近7天的账单金额趋势
            List<Double> amountData = new ArrayList<>();
            for (int i = 6; i >= 0; i--) {
                LocalDate date = today.minusDays(i);
                String dateStr = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                // 获取真实的账单总金额
                Double totalAmount = billMapper.getTotalAmountByDate(dateStr);
                amountData.add(totalAmount != null ? totalAmount : 0.0);
            }
            
            stats.put("todayCount", todayCount);
            stats.put("yesterdayCount", yesterdayCount);
            stats.put("thisWeekCount", thisWeekCount);
            stats.put("thisMonthCount", thisMonthCount);
            stats.put("todayAmount", todayAmount != null ? todayAmount : 0.0);
            stats.put("yesterdayAmount", yesterdayAmount != null ? yesterdayAmount : 0.0);
            stats.put("thisWeekAmount", thisWeekAmount != null ? thisWeekAmount : 0.0);
            stats.put("thisMonthAmount", thisMonthAmount != null ? thisMonthAmount : 0.0);
            stats.put("weeklyData", weeklyData);
            stats.put("weeklyLabels", weeklyLabels);
            stats.put("amountData", amountData);
            
            return R.createSuccess(stats);
        } catch (Exception e) {
            e.printStackTrace();
            return R.createError(StatusCode.ERROR, "获取统计数据失败：" + e.getMessage());
        }
    }

}
